#include <iostream>
#include <signal.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>

using namespace std;

int flag = 0;

pid_t id;

void handler1(int sig){
    cout << "chage flag 0 to 1" << endl;
    flag = 1;
}

void handler2(int signo){
    


    while(1){
        cout << "catch signo:" << signo << " pid:" << getpid() << endl;
        sleep(2);
        //非阻塞等待，当此时没有可回收的子进程就结束，直到再次收到子进程的退出信号时再进入handler
        pid_t ret = waitpid(-1, NULL, WNOHANG);
        if(ret>0){
            cout << "wait success,ret:" << ret << " id:" << id << endl;
        }else{
            break;
        }
    }

    cout << "handler done" << endl;
}

int main(){

    // signal(2, handler);
    // while (!flag){

    // }
    // cout << "process quit normal" << endl;


    //捕捉子进程的退出信号
    signal(SIGCHLD, handler2);
    //不通知父进程，直接回收退出的子进程
    signal(SIGCHLD, SIG_IGN);
    for (int i = 0; i < 5; i++)
    {
        id = fork();
        if(id == 0){
            int cnt = 5;
            while(cnt){
                cout <<"child" << i << " pid:" << getpid() << " ppid:" << getppid() << endl;
                sleep(1);
                cnt--;
            }
            cout <<"child " << i << " exit" << endl;
            exit(-1);
        }
    }

    while(1){
        
    }

    return 0;
}